import { Message} from 'element-ui'

export default ( (app) => {

  app.$axios.defaults.baseURL = app.$axios.defaults.baseURL + 'api';

  app.$axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

  //请求拦截器
  app.$axios.onRequest(config => {
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false
    //获取token
    let token = app.$getToken();
    if(token && !isToken){
      //让每个请求携带自定义token
      config.headers['Authorization'] = 'Bearer ' + token;
    }
    return config;
  })

  //响应拦截器
  app.$axios.onResponse( response => {
    //判断token是否失效
    if(response.data.code === 401){
      app.$removeToken();
      app.$cookies.remove("isLogin");
      app.store.commit('user/DEL_LOGIN');
      Message({
        message: "您暂未登录或登录已失效，请重新登录",
        type: 'warning',
        duration: process.env.MSG_TIME,
        onClose: function () {
          app.redirect("/login?redirect=" + app.route.path);
        }
      })
    }
    return response.data;
  })

  //错误拦截器
  app.$axios.onResponseError(error => {
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({
      message: message,
      type: 'error',
      duration: process.env.MSG_TIME
    })
  })

})
